package org.gbif.agi.service.schedule;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gbif.agi.service.TaxonManager;
import org.gbif.scheduler.model.Job;
import org.gbif.scheduler.scheduler.Launchable;
import org.gbif.util.JSONUtils;

/**
 * A wrapper class that will allow for the serializing and de-serializing of an operation against
 * a datasource.
 * 
 * @author timrobertson
 */
public class TieTaxonomyLauncher implements Launchable {
	protected static Log log = LogFactory.getLog(TieTaxonomyLauncher.class);
	
	
	// these are the keys for that will be stored in the job, to allow for the serialization
	public static final String DATASOURCE_ID = "agi:datasoureId";
	
	protected TaxonManager taxonManager;
	
	public static Job createJob(Long datasourceId) {		
		// build the data
		Map<String, Object> jobData = new HashMap<String, Object>();
		jobData.put(TieTaxonomyLauncher.DATASOURCE_ID, datasourceId);
		String jobDataAsJSON = JSONUtils.jsonFromMap(jobData);
		
		Job job = new Job();
		job.setJobClassName(TieTaxonomyLauncher.class.getName());
		job.setDataAsJSON(jobDataAsJSON);
		job.setJobGroup("TieTaxonomy");
		job.setName("Taxonomy tying for datasourceId:" + datasourceId);
		job.setRunningGroup("datasource:"+datasourceId);
		return job;
	}
	
	@SuppressWarnings("unchecked")
	public void launch(Map<String, Object> jobData) throws Exception {
		String datasourceIdAsString = (String) jobData.get(TieTaxonomyLauncher.DATASOURCE_ID);
		if (datasourceIdAsString != null) {
			Long datasourceId = Long.parseLong(datasourceIdAsString);
			log.debug("Launching Tie Taxonomy for datasourceId[" + datasourceId + "]");
			taxonManager.tieGeneraToTaxonomy(datasourceId);			
		} else {
			log.error("Unable to tie taxonomy as Job is corrupt - no datasource id");
		}
	}

	public TaxonManager getTaxonManager() {
		return taxonManager;
	}

	public void setTaxonManager(TaxonManager taxonManager) {
		this.taxonManager = taxonManager;
	}
}
